<?php  
class ControllerProductProduct extends Controller {
	private $error = array(); 
	
	public function index() {
		
		$this->document->addScript('catalog/view/javascript/jquery/jqzoom/jquery.jqzoom-core.js');
		$this->document->addStyle('catalog/view/javascript/jquery/jqzoom/jquery.jqzoom.css');
		
		$this->language->load('product/product');
		$this->load->model('catalog/manufacturer');
		$this->load->model('catalog/category');	
		$this->load->model('promotion/promotion');
		$this->load->model('catalog/review');
	
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link(),			
			'separator' => false
		);
		
		$routeRewrite = '';
		if (isset($this->request->get['routeSource'])){
			$route = $this->request->get['routeSource'];
		}else{
			$route = '';
		}
		
		if (isset($this->request->get['category_id'])){
			$categoryId = $this->request->get['category_id'];
		}else{
			$categoryId = '';
		}
		if($route){
			if($route == ROUTE_SEARCH_R){
				if (isset($this->request->get['keyword'])) {
					$routeRewrite = $this->request->get['keyword'];
					$this->data['breadcrumbs'][] = array(
			       		'text'      => $routeRewrite,
						'href'      => $this->url->linkRewrite($route, $routeRewrite),
			      		'separator' => $this->language->get('text_separator')
			   		);
				}
				
			}else if($route == ROUTE_PROMOTION_R){
				if (isset($this->request->get['promotion_id'])) {
					$promotionId = $this->request->get['promotion_id'];
					$promotion_info = $this->model_promotion_promotion->getActivityById($promotionId);
					$routeRewrite = $promotion_info['name'];
					$this->data['breadcrumbs'][] = array(
			       		'text'      => $routeRewrite,
						'href'      => $this->url->linkRewrite($route, $routeRewrite),
			      		'separator' => $this->language->get('text_separator')
			   		);
				}
			}else {
				$this->data['breadcrumbs'][] = array(
		       		'text'      => $route,
					'href'      => $this->url->linkRewrite($route),
		      		'separator' => $this->language->get('text_separator')
		   		);
			}
		}
		
		if ($categoryId) {
			$path = '';
			foreach (explode('_', $categoryId) as $path_id) {
				if (!$path) {
					$path = $path_id;
				} else {
					$path .= '_' . $path_id;
				}
				$category_info = $this->model_catalog_category->getCategory($path_id);
				if ($category_info) {
					if($routeRewrite){
						$routeRewrite_t = $routeRewrite;
					}else{
						$routeRewrite_t = $category_info['name'];
					}
					$this->data['breadcrumbs'][] = array(
						'text'      => $category_info['name'],
						'href'      => $this->url->linkRewrite($route, $routeRewrite_t . '_c' . $path),
						'separator' => $this->language->get('text_separator')
					);
				}
			}
		}
		
		if (isset($this->request->get['product_id'])) {
			$product_id = $this->request->get['product_id'];
		} else {
			$product_id = 0;
		}
		$this->load->model('catalog/product');
		$product_info = $this->model_catalog_product->getProduct($product_id);
		$this->data['product_info'] = $product_info;
		if ($product_info) {
			if($routeRewrite){
				$routeRewrite_t = $routeRewrite;
			}else{
				$routeRewrite_t = $product_info['name'];
			}
			if($categoryId){
				$categoryId_t = '_' . $categoryId;
			}else{
				$categoryId_t = '';
			}
			$this->data['productPath'] = $this->url->linkRewrite($route, $routeRewrite_t . '_p' . $product_id . $categoryId_t);
			$this->data['breadcrumbs'][] = array(
				'text'      => $product_info['name'],
				'href'      => $this->url->linkRewrite($route, $routeRewrite_t . '_p' . $product_id . $categoryId_t),
				'separator' => $this->language->get('text_separator')
			);			
			
			$this->document->setTitle($product_info['name']);
			$this->document->setDescription($product_info['meta_description']);
			$this->document->setKeywords($product_info['meta_keyword']);
			$this->document->addLink($this->url->linkRewrite($route, $routeRewrite_t . '_p' . $product_id . $categoryId_t), 'canonical');
			
			$this->data['heading_title'] = $product_info['name'];
			
			$this->data['text_select'] = $this->language->get('text_select');
			$this->data['text_manufacturer'] = $this->language->get('text_manufacturer');
			$this->data['text_discount'] = $this->language->get('text_discount');
			$this->data['text_price'] = $this->language->get('text_price');
			$this->data['text_discount'] = $this->language->get('text_discount');
			$this->data['text_option'] = $this->language->get('text_option');
			$this->data['text_qty'] = $this->language->get('text_qty');
			$this->data['text_minimum'] = sprintf($this->language->get('text_minimum'), $product_info['minimum']);
			$this->data['text_or'] = $this->language->get('text_or');
			$this->data['text_write'] = $this->language->get('text_write');
			$this->data['text_note'] = $this->language->get('text_note');
			$this->data['text_share'] = $this->language->get('text_share');
			$this->data['text_wait'] = $this->language->get('text_wait');
			$this->data['text_tags'] = $this->language->get('text_tags');
			$this->data['text_related'] = $this->language->get('text_related');
			$this->data['text_related_kw'] = $this->language->get('text_related_kw');
			
			$this->data['entry_name'] = $this->language->get('entry_name');
			$this->data['entry_review'] = $this->language->get('entry_review');
			$this->data['entry_rating'] = $this->language->get('entry_rating');
			$this->data['entry_good'] = $this->language->get('entry_good');
			$this->data['entry_bad'] = $this->language->get('entry_bad');
			$this->data['entry_captcha'] = $this->language->get('entry_captcha');
			
			$this->data['button_cart'] = $this->language->get('button_cart');
			$this->data['button_wishlist'] = $this->language->get('button_wishlist');
			$this->data['button_upload'] = $this->language->get('button_upload');
			$this->data['button_continue'] = $this->language->get('button_continue');
			
			

			$this->data['tab_description'] = $this->language->get('tab_description');
			$this->data['tab_attribute'] = $this->language->get('tab_attribute');
			$this->data['tab_review'] = sprintf($this->language->get('tab_review'), $product_info['reviews']);
			$this->data['tab_related'] = $this->language->get('tab_related');
			
			$this->data['product_id'] = $this->request->get['product_id'];
			$this->data['model'] = $product_info['model'];
			$this->data['points'] = $product_info['points'];
						
			$this->load->model('tool/image');
			if ($product_info['image']) {
				$this->data['image_add'] = $this->model_tool_image->resize($product_info['image'], $this->config->get('config_image_additional_width'), $this->config->get('config_image_additional_height'));
				$imgHD = $this->model_tool_image->resizeAndHD($product_info['image'], $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
				$this->data['image_thumb'] = $imgHD[0];
				if($imgHD[1]){
					$this->data['image_big'] = $this->model_tool_image->fullPath($product_info['image']);
				}else{
					$this->data['image_big'] = '';
				}
			} else {
				$this->data['image_add'] = '';
				$this->data['image_thumb'] = '';
				$this->data['image_big'] = '';
			}
			
			$this->data['images'] = array();
			$results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);
			foreach ($results as $result) {
				$imgHD = $this->model_tool_image->resizeAndHD($result['image'], $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
				$img_thumb = $imgHD[0];
				if($imgHD[1]){
					$img_big = $this->model_tool_image->fullPath($result['image']);
				}else{
					$img_big = '';
				}
				$this->data['images'][] = array(
					'add' => $this->model_tool_image->resize($result['image'], $this->config->get('config_image_additional_width'), $this->config->get('config_image_additional_height')),
					'thumb' => $img_thumb,
					'big' => $img_big
				);
			}	
						
			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$this->data['price'] = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
			} else {
				$this->data['price'] = false;
			}
						
			if ((float)$product_info['special']) {
				$this->data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
			} else {
				$this->data['special'] = false;
			}
			
			$discounts = $this->model_catalog_product->getProductDiscounts($this->request->get['product_id']);
			$this->data['discounts'] = array(); 
			foreach ($discounts as $discount) {
				$this->data['discounts'][] = array(
					'quantity' => $discount['quantity'],
					'price'    => $this->currency->format($this->tax->calculate($discount['price'], $product_info['tax_class_id'], $this->config->get('config_tax')))
				);
			}
			
			$this->data['options'] = array();
			foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) { 
				if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') { 
					$option_value_data = array();
					
					foreach ($option['option_value'] as $option_value) {
						if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
							if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
								$price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
							} else {
								$price = false;
							}
							
							$option_value_data[] = array(
								'product_option_value_id' => $option_value['product_option_value_id'],
								'option_value_id'         => $option_value['option_value_id'],
								'name'                    => $option_value['name'],
								'image'                   => $this->model_tool_image->resize($option_value['image'], 50, 50),
								'price'                   => $price,
								'price_prefix'            => $option_value['price_prefix']
							);
						}
					}
					
					$this->data['options'][] = array(
						'product_option_id' => $option['product_option_id'],
						'option_id'         => $option['option_id'],
						'name'              => $option['name'],
						'type'              => $option['type'],
						'option_value'      => $option_value_data,
						'required'          => $option['required']
					);					
				} elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
					$this->data['options'][] = array(
						'product_option_id' => $option['product_option_id'],
						'option_id'         => $option['option_id'],
						'name'              => $option['name'],
						'type'              => $option['type'],
						'option_value'      => $option['option_value'],
						'required'          => $option['required']
					);						
				}
			}
							
			if ($product_info['minimum']) {
				$this->data['minimum'] = $product_info['minimum'];
			} else {
				$this->data['minimum'] = 1;
			}
			
			$this->data['review_status'] = $this->config->get('config_review_status');
			$this->data['reviews'] = sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']);
			$this->data['rating'] = (int)$product_info['rating'];
			$this->data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');
			$this->data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
			
			$this->data['products'] = array();
			$results = $this->model_catalog_product->getProductRelated($this->request->get['product_id'], 8);
			if(count($results) < 10){
				$results2 = $this->model_catalog_product->getProductRelatedAuto($this->request->get['product_id'], 16);
				if($results2){
					$results = $results + $results2;
					$results = array_slice($results, 0, 8);
				}
			}
			foreach ($results as $result) {
				if ($result['image']) {
					$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_related_width'), $this->config->get('config_image_related_height'));
				} else {
					$image = false;
				}
				if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
					$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
				} else {
					$price = false;
				}
				if ((float)$result['special']) {
					$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
				} else {
					$special = false;
				}
				if ($this->config->get('config_review_status')) {
					$rating = (int)$result['rating'];
				} else {
					$rating = false;
				}
				$this->data['products'][] = array(
					'product_id' => $result['product_id'],
					'thumb'   	 => $image,
					'name'    	 => $result['name'],
					'price'   	 => $price,
					'special' 	 => $special,
					'rating'     => $rating,
					'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
					'href'    	 => $this->url->linkRewrite('', $result['name'] . '_p' . $result['product_id']),
				);
			}	
			
			$this->data['tags'] = array();
			$results = $this->model_catalog_product->getProductTags($this->request->get['product_id']);
			foreach ($results as $result) {
				$this->data['tags'][] = array(
					'tag'  => $result['tag'],
					'href' => $this->url->linkRewrite(ROUTE_SEARCH_R, $result['tag'])
				);
			}
			
			$this->model_catalog_product->updateViewed($this->request->get['product_id']);
			$this->data['reviewList'] = array();
			if($product_info['reviews'] > 0){
				$this->data['text_on'] = $this->language->get('text_on');
				$results = $this->model_catalog_review->getReviewsByProductId($this->request->get['product_id'], 0, 3);
				foreach ($results as $result) {
					$text = $result['text'];
					if(strlen($text) > 150){
						$text = utf8_substr($text, 0, 150) . '...';
					}
		        	$this->data['reviewList'][] = array(
		        		'author'     => utf8_substr($result['author'], 0, 3) . '***',
						'text'       => $text,
						'rating'     => (int)$result['rating'],
		        		'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
		        		'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['rating'])
		        	);
		      	}
			}
			$this->data['morereviews'] =  $this->url->linkRewrite(ROUTE_REVIEWS_R, $product_info['name'] . '_p' . $product_info['product_id']);
			
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/product.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/product/product.tpl';
			} else {
				$this->template = 'default/template/product/product.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
			$this->response->setOutput($this->render());
		} else {
			$url = '';
			if (isset($this->request->get['category_id'])) {
				$url .= '&category_id=' . $this->request->get['category_id'];
			}		
			if (isset($this->request->get['keyword'])) {
				$url .= '&keyword=' . $this->request->get['keyword'];
			}

			$this->data['productPath'] = $this->url->link('product/product', $url . '&product_id=' . $product_id);
			
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->language->get('text_error'),
				'href'      => $this->url->link('product/product', $url . '&product_id=' . $product_id),
        		'separator' => $this->language->get('text_separator')
      		);			
		
      		$this->document->setTitle($this->language->get('text_error'));

      		$this->data['heading_title'] = $this->language->get('text_error');

      		$this->data['text_error'] = $this->language->get('text_error');

      		$this->data['button_continue'] = $this->language->get('button_continue');

      		$this->data['continue'] = $this->url->link('common/home');

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} else {
				$this->template = 'default/template/error/not_found.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
			$this->response->setOutput($this->render());
    	}
  	}
	
	public function write() {
		$this->language->load('product/product');
		
		$this->load->model('catalog/review');
		
		$json = array();
		
		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
				$json['error'] = $this->language->get('error_name');
			}
			
			if ((utf8_strlen($this->request->post['text']) < 25) || (utf8_strlen($this->request->post['text']) > 1000)) {
				$json['error'] = $this->language->get('error_text');
			}
	
			if (empty($this->request->post['rating'])) {
				$json['error'] = $this->language->get('error_rating');
			}
	
			if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
				$json['error'] = $this->language->get('error_captcha');
			}
				
			if (!isset($json['error'])) {
				$this->model_catalog_review->addReview($this->request->get['product_id'], $this->request->post);
				
				$json['success'] = $this->language->get('text_success');
			}
		}
		
		$this->response->setOutput(json_encode($json));
	}
	
	public function captcha() {
		$this->load->library('captcha');
		
		$captcha = new Captcha();
		
		$this->session->data['captcha'] = $captcha->getCode();
		
		$captcha->showImage();
	}
	
	public function upload() {
		$this->language->load('product/product');
		
		$json = array();
		
		if (!empty($this->request->files['file']['name'])) {
			$filename = basename(preg_replace('/[^a-zA-Z0-9\.\-\s+]/', '', html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8')));
			
			if ((strlen($filename) < 3) || (strlen($filename) > 64)) {
        		$json['error'] = $this->language->get('error_filename');
	  		}	  	
			
			$allowed = array();
			
			$filetypes = explode(',', $this->config->get('config_upload_allowed'));
			
			foreach ($filetypes as $filetype) {
				$allowed[] = trim($filetype);
			}
			
			if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
				$json['error'] = $this->language->get('error_filetype');
       		}	
						
			if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
				$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
			}
		} else {
			$json['error'] = $this->language->get('error_upload');
		}
		
		if (!$json) {
			if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
				$file = basename($filename) . '.' . md5(mt_rand());
				
				// Hide the uploaded file name so people can not link to it directly.
				$json['file'] = $this->encryption->encrypt($file);
				
				move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $file);
			}
						
			$json['success'] = $this->language->get('text_upload');
		}	
		
		$this->response->setOutput(json_encode($json));		
	}
}
?>